package cdu.javaendwork.Controller.Shopping;

import cdu.javaendwork.model.sqlModel.Goods;
import cdu.javaendwork.model.sqlModel.Items;
import cdu.javaendwork.model.sqlModel.Order;
import cdu.javaendwork.model.sqlModel.User;
import cdu.javaendwork.service.Impl.Shopping.GoodsServiceImpl;
import cdu.javaendwork.service.Impl.Shopping.ItemsServiceImpl;
import cdu.javaendwork.service.Impl.Shopping.OrderServiceImpl;
import cdu.javaendwork.service.Interface.Shopping.GoodsService;
import cdu.javaendwork.service.Interface.Shopping.ItemsService;
import cdu.javaendwork.service.Interface.Shopping.OrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

@WebServlet("/items_mod")
public class ItemsModController extends HttpServlet {
    OrderService orderService = new OrderServiceImpl();
    GoodsService goodsService = new GoodsServiceImpl();
    ItemsService itemsService = new ItemsServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //拿到页码
        String sPage=req.getParameter("page");
        int page=(sPage == null || sPage.equals("")) ? 1 : Integer.parseInt(sPage);
        //拿到修改数量
        String gcnt = req.getParameter("good_cnt");
        int good_cnt = Integer.parseInt(gcnt);
        //拿到要修改的条目id
        String iid = req.getParameter("itemsid");
        int itemsid = Integer.parseInt(iid);
        //拿到登录用户的id
        HttpSession session = req.getSession();
        User user= (User)session.getAttribute("user");
        int userid = user.getId();
        //如果修改数量为0等于删除 转发去删除
        if(good_cnt == 0)
        {
            req.getRequestDispatcher("items_delete").forward(req,resp);
            return ;
        }

        //查询到原条目与相关商品以及购物车 并计算价格
        Items oldItems = itemsService.findById(itemsid);
        Goods goods = goodsService.findById(oldItems.getGoodid());
        Order craft = orderService.findById(oldItems.getOrderid());
        BigDecimal oldPrice = oldItems.getPrice();
        BigDecimal nowPrice = goods.getPrice().multiply(new BigDecimal(good_cnt));
        BigDecimal differPrice = new BigDecimal(nowPrice.doubleValue()-oldPrice.doubleValue());
        //新增新的条目
        itemsService.insert(oldItems.getOrderid(),goods.getId(),good_cnt,nowPrice);
        //删除原来的条目
        itemsService.delete(oldItems.getId());
        //修改购物车价格
        BigDecimal nowCraftPrice = craft.getPrice().add(differPrice);
        orderService.update(craft.getId(),userid,1,new Timestamp(new Date().getTime()),nowCraftPrice,"");

        //修改完成回到原页面的原页码
        req.getRequestDispatcher("craft").forward(req,resp);
    }
}
